package com.qf.controller;

import com.qf.service.IUserService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@CrossOrigin
public class ImgController {
    @Autowired
    private IUserService userService;

    private String path = "D:\\IdeaProjects\\SpringBoot\\GoGame\\src\\main\\resources\\upload\\uploadImg\\";

    //上传图片
    @RequestMapping("/img/uploader")
    public String uploaderImg(String username, MultipartFile file) {
        System.out.println("获取到上传头像的用户：" + username);
        //这里一定要教file
        //基于UUID生成一个文件名（防止上传图片重复）
        String fileName = UUID.randomUUID().toString();
        //IO流
        try (
                InputStream in = file.getInputStream();
                OutputStream out = new FileOutputStream(path + fileName);
        ) {
            IOUtils.copy(in, out);
            //最新的头像名称更新到数据库
            userService.updateHeadr(username, fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("触发了文件上传：" + file.getOriginalFilename() + "：正在上传");
        return fileName;
    }

    //通过图片名称获取图片内容
    @RequestMapping("/img/getImg")
    public void getImg(String imgName, HttpServletResponse response) {
        //获取本地图片
        try (
                InputStream in = new FileInputStream(path + imgName);
                OutputStream out = response.getOutputStream();
        ) {
            IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
